package seckill

import (
	"context"
	"encoding/json"
	"fmt"
	"time"

	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/product"
	"github.com/flipped-aurora/gin-vue-admin/server/model/seckill"
	seckillReq "github.com/flipped-aurora/gin-vue-admin/server/model/seckill/request"
)

type SeckillActivityService struct{}

// CreateSeckillActivity 创建秒杀活动记录
// Author [yourname](https://github.com/yourname)
func (seckillActivityService *SeckillActivityService) CreateSeckillActivity(ctx context.Context, seckillActivity *seckill.SeckillActivity) (err error) {
	var seckills seckill.SeckillActivity
	err = global.GVA_DB.Where("product_id = ?", *seckillActivity.ProductId).Find(&seckills).Error
	if seckills.ProductId != nil {
		s := *seckillActivity.StartTime
		e := *seckillActivity.EndTime
		if (s.Unix() < (*seckills.StartTime).Unix() && (*seckills.StartTime).Unix() < e.Unix()) || (s.Unix() < (*seckills.EndTime).Unix() && e.Unix() > (*seckills.EndTime).Unix()) || (s.Unix() > (*seckills.StartTime).Unix() && e.Unix() < (*seckills.EndTime).Unix()) {
			return fmt.Errorf("同一商品活动时间不能重叠")
		}
	}
	prokey := fmt.Sprintf("product:%d", *seckillActivity.ProductId)
	seckey := fmt.Sprintf("product:seckill:%d", *seckillActivity.ProductId)
	stock, _ := global.Redis.Get(context.Background(), prokey).Result()
	if stock == "" {
		return fmt.Errorf("库存不足")
	}
	products := product.Product{}
	json.Unmarshal([]byte(stock), &products)
	if *products.Stock < *seckillActivity.SeckillStock {
		return fmt.Errorf("库存不足")
	}
	*products.Stock -= *seckillActivity.SeckillStock
	prodata, _ := json.Marshal(products)
	secdata, _ := json.Marshal(seckillActivity)
	global.Redis.Set(context.Background(), prokey, string(prodata), 0)
	global.Redis.Set(context.Background(), seckey, string(secdata), 0)
	err = global.GVA_DB.Create(seckillActivity).Error
	return err
}

// DeleteSeckillActivity 删除秒杀活动记录
// Author [yourname](https://github.com/yourname)
func (seckillActivityService *SeckillActivityService) DeleteSeckillActivity(ctx context.Context, activityId string) (err error) {
	var seckills seckill.SeckillActivity
	err = global.GVA_DB.Where("product_id = ?", activityId).Find(&seckills).Error
	if seckills.ProductId != nil {
		n := time.Now()
		if n.Unix() > (*seckills.StartTime).Unix() && n.Unix() < (*seckills.EndTime).Unix() {
			return fmt.Errorf("正在进行的活动不能删除")
		}
	}
	err = global.GVA_DB.Delete(&seckill.SeckillActivity{}, "activity_id = ?", activityId).Error
	return err
}

// DeleteSeckillActivityByIds 批量删除秒杀活动记录
// Author [yourname](https://github.com/yourname)
func (seckillActivityService *SeckillActivityService) DeleteSeckillActivityByIds(ctx context.Context, activityIds []string) (err error) {
	err = global.GVA_DB.Delete(&[]seckill.SeckillActivity{}, "activity_id in ?", activityIds).Error
	return err
}

// UpdateSeckillActivity 更新秒杀活动记录
// Author [yourname](https://github.com/yourname)
func (seckillActivityService *SeckillActivityService) UpdateSeckillActivity(ctx context.Context, seckillActivity seckill.SeckillActivity) (err error) {
	var seckills seckill.SeckillActivity
	err = global.GVA_DB.Where("product_id = ?", *seckillActivity.ProductId).Find(&seckills).Error
	if seckills.ProductId != nil {
		n := time.Now()
		if n.Unix() > (*seckills.StartTime).Unix() && n.Unix() < (*seckills.EndTime).Unix() {
			return fmt.Errorf("正在进行的活动不能修改")
		}
	}
	err = global.GVA_DB.Model(&seckill.SeckillActivity{}).Where("activity_id = ?", seckillActivity.ActivityId).Updates(&seckillActivity).Error
	return err
}

// GetSeckillActivity 根据activityId获取秒杀活动记录
// Author [yourname](https://github.com/yourname)
func (seckillActivityService *SeckillActivityService) GetSeckillActivity(ctx context.Context, activityId string) (seckillActivity seckill.SeckillActivity, err error) {
	err = global.GVA_DB.Where("activity_id = ?", activityId).First(&seckillActivity).Error
	return
}

// GetSeckillActivityInfoList 分页获取秒杀活动记录
// Author [yourname](https://github.com/yourname)
func (seckillActivityService *SeckillActivityService) GetSeckillActivityInfoList(ctx context.Context, info seckillReq.SeckillActivitySearch) (list []seckill.SeckillActivity, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&seckill.SeckillActivity{})
	var seckillActivitys []seckill.SeckillActivity
	// 如果有条件搜索 下方会自动创建搜索语句

	if info.Status != nil && *info.Status != "" {
		db = db.Where("status = ?", *info.Status)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&seckillActivitys).Error
	return seckillActivitys, total, err
}
func (seckillActivityService *SeckillActivityService) GetSeckillActivityPublic(ctx context.Context, activityId string) error {
	// 此方法为获取数据源定义的数据
	// 请自行实现
	err := global.GVA_DB.Model(&seckill.SeckillActivity{}).Where("activity_id = ?", activityId).Update("status", "0").Error
	return err
}
